import { ref } from 'vue'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore(
  'userStore',
  () => {
    const lastid = ref(41200)
    const token = ref('')
    const user = ref({
      id: 1,
      username: '',
      password: '',
      email: '',
      userAvator: ''
    })
    const users = ref([
      {
        id: 1,
        username: '星空',
        password: 'dxf123456',
        email: '2812964847@qq.com',
        userAvator: ''
      }
    ])
    //设置当前用户
    const setUser = (username: string, password: string) => {
      //检查是否存在用户
      const userToUpdate = users.value.find(
        (user) => user.username === username
      )

      if (!userToUpdate) {
        ElMessage.error('未找到用户信息')
        return
      }
      if (!users.value.some((user) => user.password === password)) {
        ElMessage.error('密码错误!')
        return
      }

      user.value.id = userToUpdate.id
      user.value.username = userToUpdate.username
      user.value.password = userToUpdate.password
      user.value.email = userToUpdate.email
      token.value = `${user.value.id}`
      ElMessage.success('登录成功！')
    }
    //添加用户
    const addUser = (
      id: number,
      username: string,
      email: string,
      password: string
    ) => {
      users.value.push({
        id,
        username,
        password,
        email,
        userAvator: ''
      })
      console.log(users.value)
      lastid.value += 1
    }
    //设置头像
    const setAvator = () => {}

    return { token, user, users, lastid, addUser, setUser, setAvator }
  },
  {
    persist: true
  }
)
